package com.thirdlib.test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.curry.android.adapter.FatherAdapter;

public abstract class BeanAdapter<T> extends FatherAdapter<T> {
	private Context context;
	private int resource;
	private LayoutInflater mInflater;
	private List<Map<String,Object>> list;
	private Map<Integer,View> views;
    private View view;
	public BeanAdapter(Context context, int mResource, List<Map<String,Object>> list) {
		this.context = context;
		this.resource = mResource;
		this.list = list;
		views = new HashMap<>();
		mInflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			view = mInflater.inflate(resource, parent, false);
		} else {
			view = convertView;
		}
		bindView(view, position, (List<Map<String, Object>>) list);
		return view;
	}

	public abstract void bindView(View view, int position,
			List<Map<String, Object>> list);

	public class ViewHolder {
		Map<Integer, View> views;

		@SuppressLint("UseSparseArrays")
		public ViewHolder() {
			super();
			views = new HashMap<Integer, View>();
		}

		public void put(Integer id, View v) {
			views.put(id, v);
		}

		public View get(Integer id) {
			return views.get(id);
		}

	}
	
	@SuppressWarnings("unchecked")
	@Override
	public BaseAdapter setList(List<T> list) {
		this.list = (List<Map<String, Object>>) list;
		return this;
	}

	private BeanAdapter setText(int viewId,String value){
		View v = retrieveView(viewId);
		if(v instanceof TextView){
			((TextView)v).setText(value);
		}else{
		}
		return this;
	}

	private <T extends View> T retrieveView(int viewId) {
		View viewRetrieve = views.get(viewId);
		if(viewRetrieve==null){
			viewRetrieve = view.findViewById(viewId);
			views.put(viewId,view);
		}
		return (T)view;
	}

}
